<template>
  <div class="customer-service-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">客服咨询管理</span>
          <div class="header-actions">
            <el-button 
              type="success" 
              :icon="isConnected ? 'Connection' : 'Connection'" 
              :disabled="isConnected"
              @click="connectWebSocket"
            >
              {{ isConnected ? '已连接' : '连接客服' }}
            </el-button>
            <el-badge :value="unreadCount" :hidden="unreadCount === 0">
              <el-button :icon="Bell">未读消息</el-button>
            </el-badge>
          </div>
        </div>
      </template>

      <div class="service-layout">
        <!-- 左侧会话列表 -->
        <div class="conversation-list">
          <div class="search-bar">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索用户..."
              :prefix-icon="Search"
              clearable
            />
          </div>

          <el-scrollbar height="calc(100vh - 280px)">
            <div 
              v-for="conv in filteredConversations" 
              :key="conv.user_id"
              class="conversation-item"
              :class="{ active: activeUserId === conv.user_id }"
              @click="selectConversation(conv)"
            >
              <el-badge :value="conv.unread_count" :hidden="conv.unread_count === 0">
                <el-avatar :size="40" :src="conv.avatar">
                  {{ conv.username?.charAt(0) }}
                </el-avatar>
              </el-badge>
              
              <div class="conv-info">
                <div class="conv-header">
                  <span class="username">{{ conv.username }}</span>
                  <span class="time">{{ formatTime(conv.last_message_time) }}</span>
                </div>
                <div class="last-message">{{ conv.last_message }}</div>
              </div>
            </div>

            <el-empty 
              v-if="filteredConversations.length === 0" 
              description="暂无会话"
              :image-size="100"
            />
          </el-scrollbar>
        </div>

        <!-- 右侧聊天区域 -->
        <div class="chat-area">
          <template v-if="activeUserId">
            <!-- 聊天头部 -->
            <div class="chat-header">
              <div class="user-info">
                <el-avatar :size="36" :src="activeConversation?.avatar">
                  {{ activeConversation?.username?.charAt(0) }}
                </el-avatar>
                <div class="info">
                  <div class="username">{{ activeConversation?.username }}</div>
                  <div class="status">在线</div>
                </div>
              </div>
              <div class="actions">
                <el-button :icon="UserFilled" link @click="viewUserInfo">查看资料</el-button>
                <el-button :icon="Delete" link type="danger" @click="clearHistory">清空记录</el-button>
              </div>
            </div>

            <!-- 消息列表 -->
            <el-scrollbar ref="messageScrollbar" class="message-list">
              <div class="messages">
                <div 
                  v-for="msg in currentMessages" 
                  :key="msg.id"
                  class="message-item"
                  :class="msg.sender_type"
                >
                  <el-avatar v-if="msg.sender_type === 'user'" :size="32">
                    {{ activeConversation?.username?.charAt(0) }}
                  </el-avatar>
                  
                  <div class="message-content">
                    <div class="message-bubble">
                      <div class="text">{{ msg.content }}</div>
                    </div>
                    <div class="message-time">{{ formatMessageTime(msg.created_at) }}</div>
                  </div>

                  <el-avatar v-if="msg.sender_type === 'admin'" :size="32">客</el-avatar>
                </div>
              </div>
            </el-scrollbar>

            <!-- 输入区域 -->
            <div class="input-area">
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="3"
                placeholder="输入消息..."
                @keydown.enter.ctrl="sendMessage"
              />
              <div class="input-actions">
                <span class="tip">Ctrl + Enter 发送</span>
                <el-button type="primary" :icon="Promotion" @click="sendMessage">发送</el-button>
              </div>
            </div>
          </template>

          <el-empty 
            v-else 
            description="请选择一个会话开始聊天"
            :image-size="200"
          />
        </div>
      </div>
    </el-card>

    <!-- 用户信息对话框 -->
    <el-dialog v-model="userInfoDialogVisible" title="用户信息" width="500px">
      <el-descriptions :column="1" border v-if="activeConversation">
        <el-descriptions-item label="用户ID">{{ activeConversation.user_id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ activeConversation.username }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ activeConversation.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ activeConversation.email || '-' }}</el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ activeConversation.created_at || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Bell, UserFilled, Delete, Promotion } from '@element-plus/icons-vue'

// 状态管理
const isConnected = ref(false)
const activeUserId = ref(null)
const searchKeyword = ref('')
const inputMessage = ref('')
const userInfoDialogVisible = ref(false)
const messageScrollbar = ref(null)

// WebSocket连接
let ws = null

// 会话列表
const conversations = ref([
  // 示例数据
  {
    user_id: 1,
    username: '张三',
    avatar: '',
    last_message: '你好，我想咨询一下...',
    last_message_time: new Date().toISOString(),
    unread_count: 2
  },
  {
    user_id: 2,
    username: '李四',
    avatar: '',
    last_message: '谢谢',
    last_message_time: new Date(Date.now() - 3600000).toISOString(),
    unread_count: 0
  }
])

// 消息列表（按用户分组）
const messagesMap = ref({
  1: [
    {
      id: 1,
      sender_type: 'user',
      content: '你好，我想咨询一下健身计划',
      created_at: new Date(Date.now() - 3600000).toISOString()
    },
    {
      id: 2,
      sender_type: 'admin',
      content: '您好，请问您有什么具体需求吗？',
      created_at: new Date(Date.now() - 3000000).toISOString()
    }
  ],
  2: []
})

// 计算属性
const unreadCount = computed(() => {
  return conversations.value.reduce((sum, conv) => sum + conv.unread_count, 0)
})

const filteredConversations = computed(() => {
  if (!searchKeyword.value) {
    return conversations.value
  }
  return conversations.value.filter(conv => 
    conv.username.includes(searchKeyword.value)
  )
})

const activeConversation = computed(() => {
  return conversations.value.find(conv => conv.user_id === activeUserId.value)
})

const currentMessages = computed(() => {
  return messagesMap.value[activeUserId.value] || []
})

// 方法
const connectWebSocket = () => {
  // 获取管理员信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const adminId = userInfo.id || Date.now()
  
  // 连接到管理端后台的 WebSocket (端口 8000)
  const wsUrl = `ws://localhost:8000/api/customer-service/ws/service1`
  console.log('🔌 [管理端前端] 连接 WebSocket:', wsUrl)
  
  ws = new WebSocket(wsUrl)
  
  ws.onopen = () => {
    console.log('✅ [管理端前端] WebSocket 连接成功')
    isConnected.value = true
    ElMessage.success('客服连接成功')
  }
  
  ws.onmessage = (event) => {
    console.log('📨 [管理端前端] 收到消息:', event.data)
    try {
      const data = JSON.parse(event.data)
      
      // 处理不同类型的消息
      if (data.type === 'system') {
        // 系统消息
        console.log('系统消息:', data.message)
        ElMessage.info(data.message || '系统消息')
      } else if (data.type === 'user_message') {
        // 来自业务端的用户消息（通过 Redis）
        console.log('🎯 [管理端前端] 收到来自业务端的用户消息:', data)
        handleNewMessage(data)
      } else if (data.type === 'message') {
        // 其他消息
        console.log('收到一般消息:', data)
        handleNewMessage(data)
      } else {
        // 其他消息类型
        console.log('收到其他消息:', data)
      }
    } catch (e) {
      console.error('解析消息失败:', e, event.data)
    }
  }
  
  ws.onclose = () => {
    console.log('🔌 [管理端前端] WebSocket 已断开')
    isConnected.value = false
    ElMessage.warning('客服连接已断开')
  }
  
  ws.onerror = (error) => {
    console.error('❌ [管理端前端] WebSocket 错误:', error)
    ElMessage.error('连接失败')
  }
}

const selectConversation = (conv) => {
  activeUserId.value = conv.user_id
  // 标记为已读
  conv.unread_count = 0
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

const sendMessage = () => {
  if (!inputMessage.value.trim()) {
    return
  }
  
  if (!ws || ws.readyState !== WebSocket.OPEN) {
    ElMessage.error('未连接到客服系统')
    return
  }

  if (!activeUserId.value) {
    ElMessage.error('请先选择一个会话')
    return
  }

  const newMessage = {
    id: Date.now(),
    sender_type: 'admin',
    content: inputMessage.value,
    created_at: new Date().toISOString()
  }

  // 添加到消息列表
  if (!messagesMap.value[activeUserId.value]) {
    messagesMap.value[activeUserId.value] = []
  }
  messagesMap.value[activeUserId.value].push(newMessage)

  // 更新会话列表
  const conv = conversations.value.find(c => c.user_id === activeUserId.value)
  if (conv) {
    conv.last_message = inputMessage.value
    conv.last_message_time = new Date().toISOString()
  }

  // 通过 WebSocket 发送消息到用户（需要正确格式）
  const messageData = {
    type: 'direct',  // ✅ 告诉后台这是管理员回复用户
    target: activeUserId.value,  // 目标用户ID
    content: inputMessage.value,
    timestamp: new Date().toISOString()
  }
  
  ws.send(JSON.stringify(messageData))
  console.log('📤 [管理端前端] 发送消息给用户:', messageData)

  inputMessage.value = ''
  nextTick(() => {
    scrollToBottom()
  })
}

const handleNewMessage = (data) => {
  // 处理接收到的新消息
  console.log('处理新消息:', data)
  
  // 消息可能来自 Redis（nested structure）或直接连接
  let messageData = data.message || data
  if (typeof messageData === 'string') {
    try {
      messageData = JSON.parse(messageData)
    } catch (e) {
      console.warn('消息是字符串但不能解析为JSON:', messageData)
    }
  }
  
  // 解析消息数据
  const from_user_id = messageData.from_user_id || data.from_user_id || 'unknown'
  const content = messageData.content || data.content || ''
  const timestamp = messageData.timestamp || data.timestamp || new Date().toISOString()
  
  console.log('✅ 解析后的消息:', { from_user_id, content, timestamp })
  
  // 初始化用户的消息列表
  if (!messagesMap.value[from_user_id]) {
    messagesMap.value[from_user_id] = []
  }
  
  // 添加消息
  messagesMap.value[from_user_id].push({
    id: Date.now(),
    sender_type: 'user',
    content: content,
    created_at: timestamp
  })

  // 更新会话列表
  let conv = conversations.value.find(c => c.user_id === from_user_id)
  if (!conv) {
    // 如果是新用户，创建新会话
    conv = {
      user_id: from_user_id,
      username: `用户${from_user_id}`,
      avatar: '',
      last_message: content,
      last_message_time: timestamp,
      unread_count: 1
    }
    conversations.value.unshift(conv)
  } else {
    // 更新已有会话
    conv.last_message = content
    conv.last_message_time = timestamp
    if (activeUserId.value !== from_user_id) {
      conv.unread_count++
    }
    
    // 将会话移到列表顶部
    const index = conversations.value.indexOf(conv)
    if (index > 0) {
      conversations.value.splice(index, 1)
      conversations.value.unshift(conv)
    }
  }

  // 滚动到底部
  nextTick(() => {
    if (activeUserId.value === from_user_id) {
      scrollToBottom()
    }
  })
  
  // 显示通知
  ElMessage.info(`收到来自用户${from_user_id}的新消息: ${content.substring(0, 30)}...`)
}

const viewUserInfo = () => {
  userInfoDialogVisible.value = true
}

const clearHistory = () => {
  ElMessageBox.confirm('确定要清空与该用户的聊天记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    messagesMap.value[activeUserId.value] = []
    ElMessage.success('聊天记录已清空')
  }).catch(() => {})
}

const scrollToBottom = () => {
  if (messageScrollbar.value && messageScrollbar.value.$refs && messageScrollbar.value.$refs.wrap) {
    const scrollElement = messageScrollbar.value.$refs.wrap
    scrollElement.scrollTop = scrollElement.scrollHeight
  }
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return `${date.getMonth() + 1}-${date.getDate()}`
  }
}

const formatMessageTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 生命周期
onMounted(() => {
  // 自动连接WebSocket
  connectWebSocket()
})

onUnmounted(() => {
  if (ws) {
    ws.close()
  }
})
</script>

<style scoped>
.customer-service-container {
  height: calc(100vh - 140px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.service-layout {
  display: flex;
  height: calc(100vh - 240px);
  gap: 20px;
}

/* 左侧会话列表 */
.conversation-list {
  width: 300px;
  border-right: 1px solid #e8e8e8;
  padding-right: 20px;
}

.search-bar {
  margin-bottom: 15px;
}

.conversation-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  cursor: pointer;
  border-radius: 8px;
  transition: background-color 0.3s;
  margin-bottom: 8px;
}

.conversation-item:hover {
  background-color: #f5f7fa;
}

.conversation-item.active {
  background-color: #ecf5ff;
}

.conv-info {
  flex: 1;
  overflow: hidden;
}

.conv-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.username {
  font-weight: 500;
  font-size: 14px;
}

.time {
  font-size: 12px;
  color: #999;
}

.last-message {
  font-size: 13px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 右侧聊天区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 15px;
}

.chat-header .user-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.chat-header .info .username {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
}

.chat-header .info .status {
  font-size: 12px;
  color: #67c23a;
}

.chat-header .actions {
  display: flex;
  gap: 10px;
}

/* 消息列表 */
.message-list {
  flex: 1;
  margin-bottom: 15px;
}

.messages {
  padding: 10px;
}

.message-item {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.message-item.user {
  flex-direction: row;
}

.message-item.admin {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 60%;
}

.message-item.admin .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-bubble {
  padding: 10px 15px;
  border-radius: 8px;
  word-wrap: break-word;
}

.message-item.user .message-bubble {
  background-color: #f5f7fa;
}

.message-item.admin .message-bubble {
  background-color: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 输入区域 */
.input-area {
  border-top: 1px solid #e8e8e8;
  padding-top: 15px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.tip {
  font-size: 12px;
  color: #999;
}

/* 响应式 */
@media (max-width: 768px) {
  .service-layout {
    flex-direction: column;
  }

  .conversation-list {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e8e8e8;
    padding-right: 0;
    padding-bottom: 20px;
  }
}
</style>

